<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2017/10/11
 * Time: 13:39
 */

namespace App\Http\Controllers;


use Illuminate\Support\Facades\DB;

class StudentController extends Controller
{

    /**
     * 原生DB实现CURD
     */
    public function test1(){

        //查询数据

       $students = DB::select("select * from student");
        dd($students);

       //添加数据
        /*$bool = DB::insert('insert into student(name,age) VALUES (?,?)',
            ["李四",20]);
        var_dump($bool);*/

        //更新数据
        /*$num = DB::update('update student set name = ? where name = ?',
            ["小花","李四"]);
        var_dump($num);*/

        //删除数据
        /*$num = DB::delete('delete from student WHERE id > ?',[1001]);
        var_dump($num);*/
    }

    /**
     * DB利用查询构造器新增数据
     */
    public function query1(){

        /*$bool = DB::table('student')->insert(['name' => '肖潇','age' => 17]);
        var_dump($bool);*/

        /*$id = DB::table('student')->insertGetId(['name' => '未央','age' => 20]);
        var_dump($id);*/

        $bool = DB::table('student')->insert([
            ['name' => '上官娜','age' => 19],
            ['name' => '楚乔','age' => 20],
            ['name' => '慕容晓晓','age' => 21]
        ]);

        var_dump($bool);

    }

    /**
     * DB利用查询构造器更新数据
     */
    public function query2(){
        $num = DB::table('student')
            ->where('id',1001)
            ->update(['age' => 22]);
        var_dump($num);
    }

    /**
     * DB利用查询构造器自增数据
     */
    public function query3(){
        //自增 默认自增1
        //$num = DB::table('student')->increment('age');
        //指定自增的数量
        $num = DB::table('student')->increment('age',2);
        var_dump($num);
    }

    /**
     * DB利用查询构造器自减数据
     */
    public function query4(){
        //自减 默认自减1
        //$num = DB::table('student')->decrement('age');
        //指定自减的数量
        $num = DB::table('student')->decrement('age',2);
        var_dump($num);
    }

    /**
     * 使用查询构造器删除数据
     */
    public function delete(){
        $num = DB::table('student')
            ->where('id',1003)
            ->delete();
        var_dump($num);

        //删除表结构，不删除表
        //DB::table('student')->truncate();
    }

    public function query5(){
        //$students = DB::table('student')->get();

        //$student = DB::table('student')->first();

        //多条件查询
        /*$students = DB::table('student')
            ->whereRaw('id > ? and age >= ?',[1001,20])
            ->get();*/

        //获取指定的某个字段的全部值
        //$names = DB::table('student')->pluck('name');

        //可以指定某个值作为下标
        //$names = DB::table('student')->lists('name','id');

        //可以指定查询的字段
        //$students = DB::table('student')->select('id','name','age')->get();

        //按指定行数查询
        echo "<pre>";
        DB::table('student')->chunk(2 ,function ($students){
            var_dump($students);
        });

        //dd($students);
    }

}